package com.zeropoint.demo.exception;

import com.auth0.jwt.exceptions.TokenExpiredException;
import com.zeropoint.demo.pojo.ResultEntity;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.io.IOException;

@RestControllerAdvice
public class MyExceptionHandler {

    @ExceptionHandler(value = UserLoginException.class)
    public ResultEntity<String> userLoginExceptionexceptionHandler(Exception e){
        return ResultEntity.falseWithoutData(e.getMessage());
    }


    @ExceptionHandler(value = AuthenticationException.class)
    public ResultEntity<String> authenticationExceptionexceptionHandler(Exception e){
        return ResultEntity.falseWithoutData(e.getMessage());
    }

    // 捕捉shiro的异常
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(ShiroException.class)
    public ResultEntity<String> handle401(ShiroException e) {
        return ResultEntity.falseWithoutData(e.getMessage(),"401");
    }

    // 捕捉shiro的异常
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(UnauthenticatedException.class)
    public ResultEntity<String> handle401(UnauthenticatedException e) {
        return ResultEntity.falseWithoutData("你没有权限访问","401");
    }
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(value = TokenExpiredException.class)
    public ResultEntity<String> handler(TokenExpiredException e) throws IOException {
        return ResultEntity.falseWithoutData("token已经过期，请重新登录",String.valueOf(HttpStatus.BAD_REQUEST.value()));
    }


}
